import {asyncRouterMap, constantRouterMap, outsideRouterMap} from '@/router'
import router from '@/router'

/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
function hasPermission(menus, route) {
  // console.log(menus)
  if (route.meta && route.meta.title) {
    if (route.noFilter) {
      return true
    } else {
      return menus.some(menu => route.meta.title.trim().toLowerCase() === menu.trim().toLowerCase())
    }
  } else {
    return true
  }
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param roles
 */
function filterAsyncRouter(asyncRouterMap, menus) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (hasPermission(menus, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, menus)
      }
      return true
    }
    return false
  })
  return accessedRouters
}

const permission = {
  state: {
    // routers: constantRouterMap.concat(outsideRouterMap),
    routers: constantRouterMap,
    addRouters: [],
    outsideRouterMap: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = state.routers.concat(state.addRouters)
      // state.routers = constantRouterMap.concat(routers)
    },
    SET_OUTSIDEROUTERS: (state) => {
      let newoutsideRouterMap = JSON.parse(JSON.stringify(outsideRouterMap)).map(item => {
        return Object.assign(item, {hidden: true})
      })
      state.routers = [...constantRouterMap, ...newoutsideRouterMap]
      router.addRoutes(outsideRouterMap)
      state.outsideRouterMap = outsideRouterMap
    }
  },
  actions: {
    GenerateRoutes({commit}, data) {
      return new Promise(resolve => {
        const menus = data
        let accessedRouters
        if (menus.length !== 0 && menus[0].toLowerCase() === 'all') {
          accessedRouters = asyncRouterMap
        } else {
          accessedRouters = filterAsyncRouter(asyncRouterMap, menus)
        }
        commit('SET_ROUTERS', accessedRouters)
        // commit('SET_MENUS', menus)
        commit('SET_MENUS', menus)
        resolve()
      })
    }
  }
}

export default permission
